package com.hulizuofang.wol.chat.client.presenter;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.user.client.History;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ContentSlot;
import com.gwtplatform.mvp.client.annotations.ProxyEvent;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.LockInteractionEvent;
import com.gwtplatform.mvp.client.proxy.ParameterTokenFormatter;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.Proxy;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
import com.gwtplatform.mvp.client.proxy.RevealRootContentEvent;
import com.hulizuofang.wol.chat.client.place.ClientPlaceManager;
import com.hulizuofang.wol.chat.client.place.NameTokens;
import com.hulizuofang.wol.chat.client.ui.event.changeplace.ChangePlaceEvent;
import com.hulizuofang.wol.chat.client.ui.event.changeplace.ChangePlaceHandler;

public class MainPagePresenter extends Presenter<MainPagePresenter.PageView, MainPagePresenter.PageProxy> {

	public interface PageView extends View {
		void showLoading(boolean shouldLock);
	}

	@ProxyStandard
	public interface PageProxy extends Proxy<MainPagePresenter> {}

	@Inject
	public MainPagePresenter(EventBus eventBus, PageView view, PageProxy proxy, final ClientPlaceManager clientPlaceManager) {
		super(eventBus, view, proxy);
		
		eventBus.addHandler(ChangePlaceEvent.getType(), new ChangePlaceHandler() {
			@Override
			public void onChangePlace(ChangePlaceEvent changePlaceEvent) {
				PlaceRequest placeRequest = changePlaceEvent.getPlaceRequest();
				String login = placeRequest.getParameter(NameTokens.LOGIN, "");
				
				/*
				// Apparently this is currently buggy, so I did a workaround and keep this for a better time ;)
				if ("".equals(login)) {
					clientPlaceManager.revealDefaultPlace();
				} else {
					clientPlaceManager.revealPlace(placeRequest);
				}
				*/
				
				String nameToken = placeRequest.getNameToken();
				if (!login.equals("")) {
					nameToken = new ParameterTokenFormatter().toPlaceToken(placeRequest);
				}
				
				History.newItem(nameToken);
			}
		});
	}

	@Override
	protected void revealInParent() {
		RevealRootContentEvent.fire(this, this);
	}

	/**
	 * We display a short lock message whenever navigation is in progress. 
	 * 
	 * @param event The {@link LockInteractionEvent}.
	 */
	@ProxyEvent
	public void onLockInteraction(LockInteractionEvent event) {
		getView().showLoading(event.shouldLock());
	}
	
	/**
	 * Use this in leaf presenters, inside their {@link #revealInParent} method.
	 */
	@ContentSlot
	public static final Type<RevealContentHandler<?>> TYPE_SetMainContent = new Type<RevealContentHandler<?>>();
}
